// 云函数入口文件
const cloud = require("wx-server-sdk");

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV,
});

const db = cloud.database();
const _ = db.command;

// 云函数入口函数
exports.main = async (event, context) => {
  const {
    userId, // 用户ID
    merchantId, // 商家ID
    status, // 订单状态
    page = 1, // 页码
    pageSize = 10, // 每页数量
  } = event;
  const { OPENID } = cloud.getWXContext();

  try {
    // 构建查询条件
    const query = {
      _openid: OPENID,
    };

    // 添加用户条件
    if (userId) {
      query.userId = userId;
    }

    // 添加商家条件
    if (merchantId) {
      query.merchantId = merchantId;
    }

    // 添加状态条件
    if (status) {
      query.status = status;
    }

    // 查询总数
    const countResult = await db.collection("orders").where(query).count();
    const total = countResult.total;

    // 查询列表
    const listResult = await db
      .collection("orders")
      .where(query)
      .skip((page - 1) * pageSize)
      .limit(pageSize)
      .orderBy("createTime", "desc")
      .get();

    // 获取订单详情
    const orders = await Promise.all(
      listResult.data.map(async (order) => {
        // 获取商家信息
        if (order.merchantId) {
          const merchantResult = await db
            .collection("merchants")
            .doc(order.merchantId)
            .get();
          order.merchantInfo = merchantResult.data;
        }

        // 获取用户信息
        if (order.userId) {
          const userResult = await db
            .collection("users")
            .doc(order.userId)
            .get();
          order.userInfo = userResult.data;
        }

        return order;
      })
    );

    return {
      code: 0,
      msg: "获取成功",
      data: {
        list: orders,
        total,
        page,
        pageSize,
      },
    };
  } catch (err) {
    console.error(err);
    return {
      code: -1,
      msg: "获取失败",
      error: err,
    };
  }
};
